package com.example.hyw.szysteam.myEmail;

import java.util.Date;
import java.util.Properties;
import javax.mail.*;
import javax.activation.DataHandler;
import javax.activation.FileDataSource;
import javax.mail.internet.*;
import java.io.File;
import android.util.Log;
/**
 * Created by HYW on 2018/5/19.
 */

public class MailSender {
    public boolean sendTextMail(final MailInfo mailInfo) {
        MyAuthenticator authenticator = null;// 判断是否需要身份认证
        Properties pro = mailInfo.getProperties();
        if (mailInfo.isValidate()) {
            authenticator = new MyAuthenticator(mailInfo.getUserName(), mailInfo.getPassword());// 如果需要身份认证，则创建一个密码验证器
        }
        Session sendMailSession = Session.getDefaultInstance(pro, authenticator);// 根据邮件会话属性和密码验证器构造一个发送邮件的session
        try {
            sendMailSession.setDebug(true);
            Message mailMessage = new MimeMessage(sendMailSession); // 根据session创建一个邮件消息
            Address from = new InternetAddress(mailInfo.getFromAddress());// 创建邮件发送者地址
            mailMessage.setFrom(from);// 设置邮件消息的发送者
            Address to = new InternetAddress(mailInfo.getToAddress());// 创建邮件的接收者地址，并设置到邮件消息中
            mailMessage.setRecipient(Message.RecipientType.TO, to);
            mailMessage.setSubject(mailInfo.getSubject());// 设置邮件消息的主题
            mailMessage.setSentDate(new Date());// 设置邮件消息发送的时间
            String mailContent = mailInfo.getContent();// 设置邮件消息的主要内容
            mailMessage.setText(mailContent);
            Transport.send(mailMessage);// 发送邮件
            Log.e("1","1");
            return true;
        } catch (MessagingException ex) {
            ex.printStackTrace();
            Log.e("2","2");
        }
        Log.e("3","3");
        return false;
    }
}
